<?php

class PayController extends UController
{
	/**
	 * 签名
	 */
	public function actionSign()
	{
		$is_recharge = $this->_post('is_recharge');
		$params = array(
			'no_order'    => $this->_post('no_order'),
			'money_order' => $this->_post('money_order'),//交易金额  精确到小数点后两位
			'user_id'     => $this->userId,
			'bank_id'     => $this->_post('bank_id'),
			'card_number' => $this->_post('card_number'),
			'name'        => $this->_post('name'),
			'identity'    => $this->_post('identity'),
			'bind_card'   => $is_recharge,
		);
		$data = Helper::llSign($params,$is_recharge);
		$this->setResult($data);
	}
	/**
	 * 支付前银行卡绑定判断或者充值前判断
	 */
	public function actionBeforePay()
	{
		$data = $this->getBankCardInfo();
		$this->setResult($data);
	}

	private function getBankCardInfo()
	{
		$data         = array('success'=>0);
		$user         = User::model();
		$userinfo     = $user->findById($this->userId);
		if(!$userinfo->resetPayPass)
		{
			$data['success'] = -1;
			$data['msg']     = '请先设置支付密码';
		}
		elseif(!$userinfo->authenticated)//未实名认证
		{
			$data['success'] = -2;
		}
		elseif(!$userinfo->realAuthenticated)//未真正实名认证
		{
			$data['name']     = $userinfo->name;
			$data['identity'] = $userinfo->identity;
			$card             = $user->getBankCard($this->userId);
			$cardinfo         = $card[0];
			if($cardinfo === array())
				$data['success']  = -3;
			elseif(!$cardinfo['supportLL']) //已绑卡但是不支持连连
			{
				$data['success']  = -4;
				$data['msg']      = Yii::app()->params['bankCardNotSupport'];
			}
			elseif(!$cardinfo['llMark'])
			{
				$data['success']        = -5;
				$data['bankId']         = $cardinfo['bankId'];
				$data['bankName']       = $cardinfo['bankName'];
				$data['fullCardNumber'] = $cardinfo['fullCardNumber'];
				$data['pay_limit']      = $cardinfo['payLimit']*10000;
				$data['pay_limit_desc'] = '该银行卡单笔最高可支付'.($cardinfo['payLimit']>=1?$cardinfo['payLimit']."万元":10000*$cardinfo['payLimit'].'元');
			}
		}
		else //已真正实名认证
		{
			$data['name']         = $userinfo->name;
			$data['identity']     = $userinfo->identity;
			$data['starName']     = $userinfo->starName;
			$data['starIdentity'] = $userinfo->starIdentity;
			$card                 = $user->getBankCard($this->userId);
			$cardinfo             = $card[0];
			if($cardinfo === array())
				$data['success']  = -6;
			elseif(!$cardinfo['supportLL']) //已绑卡但是不支持连连
			{
				$data['success']  = -7;
				$data['msg']      = Yii::app()->params['bankCardNotSupport'];
			}
			elseif(!$cardinfo['llMark'])
			{
				$data['success']        = -8;
				$data['bankId']         = $cardinfo['bankId'];
				$data['bankName']       = $cardinfo['bankName'];
				$data['fullCardNumber'] = $cardinfo['fullCardNumber'];
				$data['pay_limit']      = $cardinfo['payLimit']*10000;
				$data['pay_limit_desc'] = '该银行卡单笔最高可支付'.($cardinfo['payLimit']>=1?$cardinfo['payLimit']."万元":10000*$cardinfo['payLimit'].'元');
			}
			else
			{
				$data['success']        = 1;
				$data['pay_limit']      = $cardinfo['payLimit']*10000;
				$data['pay_limit_desc'] = '该银行卡单笔最高可支付'.($cardinfo['payLimit']>=1?$cardinfo['payLimit']."万元":10000*$cardinfo['payLimit'].'元');
				$data['bankId']         = $cardinfo['bankId'];
				$data['bankName']       = $cardinfo['bankName'];
				$data['cardNumber']     = $cardinfo['cardNumber'];
				$data['fullCardNumber'] = $cardinfo['fullCardNumber'];
				$data['last4number']    = $cardinfo['last4number'];
			}
		}
		if(in_array($data['success'], array(-2,-3,-4,-5,-6,-7,-8,1)))
			$data['bank_tip']       = Yii::app()->params['CCBMaintainTip'];
		return $data;
	}
	/**
	 * 设置交易密码
	 */
	public function actionSetPass()
	{
		$data         = array('success' => 0,'msg' => '');
		$password     = $this->_post('password');
		if(!$password)
			$data['msg'] = '请输入交易密码';
		elseif(strlen($password) !== 32)
			$data['msg'] = '交易密码不合法';
		else
		{
			//设置交易密码
			$remote      = HttpLib::post($this->javaApi['pay_pass_set'],array('user_id' => $this->userId,'password' => $password));
			$data['msg'] = $remote->errorMsg;
			if($remote->success)
			{
				Yii::app()->cache2->hdel($this->userId.'.Capital','UserInfo');
				$data['success']  = 1;
				$data['msg']      = '交易密码设置成功';
				$data['cardinfo'] = $this->getBankCardInfo();
			}
		}
		$this->setResult($data);
	}

	/**
	 * 忘记交易密码,给用户发送短信
	 */
	public function actionGetMobileCode()
	{
		$user = User::model();
		$info = $user->findById($this->userId);
		$data = array('success' => 0 ,'msg' => '短信验证码发送失败');
		$code = Helper::randCode($info->mobile,6,'reset_pay_pass');
		if($this->SendSms($this->userId,$info->mobile,array('file'=>'verifycode','params'=>array('code'=>$code))))
		{
			$data['success']    = 1;
			$data['msg']        = '短信验证码发送成功';
			$data['mobileCode'] = YII_DEBUG?$code:0;
			if(MOBILEOS === 'android')
                $data['mobiles'] = Yii::app()->cache_php->get('appSmsMobiles');
		}
		elseif($this->sms_disabled('reset_pay_pass'.$info->mobile,10))
            $data['msg'] = '您的手机号请求过于频繁，请明天再试';
		$this->setResult($data);
	}
	/**
	 * 重置交易密码
	 */
	public function actionResetPayPass()
	{
		$data         = array('success' => 0,'msg' => '');
		$user         = User::model();
		$info         = $user->findById($this->userId);
		$password     = $this->_post('password');
		$mobile_code  = $this->_post('mobile_code');
		if($mobile_code != Yii::app()->cache2->get('reset_pay_pass'.$info->mobile))
			$data['msg'] = '短信验证码不匹配';
		elseif(!$password)
			$data['msg'] = '请输入交易密码';
		elseif(strlen($password) !== 32)
			$data['msg'] = '交易密码不合法';
		else
		{
			//设置交易密码
			$remote      = HttpLib::post($this->javaApi['pay_pass_set'],array('user_id' => $this->userId,'password' => $password));
			$data['msg'] = $remote->errorMsg;
			if($remote->success)
			{
				$data['success'] = 1;
				$data['msg']     = '交易密码重置成功';
			}
		}
		$this->setResult($data);
	}
	/**
	 * 充值第一步
	 */
	public function actionRechargeStep1()
	{
		$data                          = $this->getBankCardInfo();
		$cap                           = User::model()->getCapital($this->userId);
		$data['capitalAccountBalance'] = $cap['capitalAccountBalance'];
		$this->setResult($data);
	}

	/**
	 * 充值完成
	 */
	public function actionRechargeDo()
	{
		$data       = array('success'=>0,'msg' => '');
		$amount     = $this->_post('amount',0);
		$bank_id  = $this->_post('bank_id');
		$password = $this->_post('password');
		$card_no  = $this->_post('card_no');
		$params = array(
			'user_id'    => $this->userId,
			'amount'     => $amount,
			'card_no'    => $card_no,
			'method'     => 0,
			'pay_method' => 3,//连连充值
		);
		$user      = User::model();
		$maxAmount = Helper::getMaxPayAmount($bank_id,3);
		Yii::trace('recharge params'.json_encode($_POST));
		Yii::trace('最大充值额度'.$maxAmount*10000);
		if($amount > $maxAmount*10000)
			$data['msg'] = '单笔最大交易额为'.($maxAmount>=1?$maxAmount.'万':10000*$maxAmount).'元';
		elseif(!$user->checkPayPass($this->userId,$password))
			$data['msg'] = '交易密码不正确';
		else
		{
			$params['bank_code'] = Helper::getBankCode($bank_id);
			$params['notice']    = '手机端'.MOBILEOS.'连连充值';
			$out_trade_no        = Helper::getTradeUUID('ll',$this->userId);
			$params['trade_no']  = $out_trade_no;
			$remote              = HttpLib::post($this->javaApi['account_recharge'], $params);
			$data['msg']         = $remote->errorMsg;
			if($remote->success)
			{
				$data['trade_no'] = $out_trade_no;
				$data['amount']   = $amount;
				$data['sign']     = '';
				$p = array(
					'user_id'     => $this->userId,
					'token'       => $this->token,
					'money_order' => $params['amount'],
					'no_order'    => $out_trade_no,
					'name'        => $this->_post('name'),
					'identity'    => $this->_post('identity'),
					'bank_id'     => $bank_id,
					'card_number' => $card_no,
					'bind_card'   => $this->_post('bindCard'),
				);
				Yii::trace('recharge sign params are'.json_encode($p));
				$is_recharge = 2;
				if($p['bind_card']==1)
					$is_recharge = 1;
				$sign        = Helper::llSign($p,$is_recharge);
				$data['msg'] = $sign['msg'];
				if($sign['success'])
				{
					$data['success']   = 1;
					$data['sign']      = $sign['sign'];
					$data['no_agree']  = $sign['no_agree'];
					$data['notifyUrl'] = $sign['notifyUrl'];
					$data['dt_order']  = $sign['dt_order'];
					$data['name']      = $sign['name'];
					$data['identity']  = $sign['identity'];
					if(!$data['no_agree'])
						unset($data['no_agree']);
				}
			}
		}
		$this->setResult($data);
	}
	/**
	 * 充值回调
	 */
	public function actionRechargeConfirm()
	{
		$data = array(
			'success' => 0,
			'msg'     => ' ',
		);
		$params = array(
			'trade_no' => $this->_post('trade_no'),
			'user_id'  => $this->userId,
		);
		if(!$params['trade_no'])
		{
			$data['msg'] = '参数不合法';
		}
		else
		{
			$remote      = HttpLib::post($this->javaApi['recharge_confirm'],$params);
			$data['msg'] = $remote->errorMsg;
			if($remote->success)
			{
				if($remote->result->status==5)
				{
					$data['success'] = 1;
					$data['msg']     = '充值成功';
					$data['amount']  = $remote->result->amount;
				}
				elseif($remote->result->status==1)
				{
					$data['success'] = 1;
					$data['msg']     = '充值形成中，由于网络原因，充值结果可能会有几分钟延迟，如有疑问请联系客服。资金账户由保险公司承保！';
					$data['amount']  = $remote->result->amount;
				}
			}
		}
		$this->setResult($data);
	}
}